package com.gitee.baqkft.code.ui.dlg;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONWriter;
import com.gitee.baqkft.code.ui.layout.GBC;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

/**
 * JSON工具
 * @Author: chenmingcai
 * @Date 2023/9/21 09:48
 **/

public class JSONToolFrame extends JFrame
{
    /**
     * 文本区
     */
    private JTextArea textArea;

    public JSONToolFrame()
    {
        setTitle("JSON工具");
        setLayout(new GridBagLayout());
        setSize(800, 400);

        GBC gbc = new GBC(0, 0, 1, 1);
        gbc.setWeight(0, 0).setFill(GBC.NONE);
        final JButton btnFormat = new JButton("格式化");
        add(btnFormat, gbc);
        btnFormat.addActionListener(this::doJsonFormat);

        gbc = new GBC(1, 0, 1, 1);
        gbc.setWeight(0, 0).setFill(GBC.NONE);
        final JButton btnCompress = new JButton("压缩");
        add(btnCompress, gbc);
        btnCompress.addActionListener(this::doJsonCompress);

        // 文本区
        textArea = new JTextArea();
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        gbc = new GBC(0, 1, 3, 1);
        gbc.setWeight(1, 1).setFill(GBC.BOTH);
        add(new JScrollPane(textArea), gbc);
    }

    /**
     * 执行格式化操作
     * @param event
     */
    private void doJsonFormat(ActionEvent event)
    {
        String text = textArea.getText().trim();
        try
        {
            Object json = JSON.parse(text);
            if(json != null)
            {
                text = JSON.toJSONString(json, JSONWriter.Feature.PrettyFormat,
                        JSONWriter.Feature.WriteMapNullValue);
                text = text.replaceAll("\t", "    ");
                textArea.setText(text);
            }
        }
        catch (JSONException ex)
        {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }

    /**
     * 执行压缩操作
     * @param event
     */
    private void doJsonCompress(ActionEvent event)
    {
        String text = textArea.getText().trim();
        Object json = JSON.parse(text);
        textArea.setText(JSON.toJSONString(json));
    }
}
